﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;

public class Async : IHttpHandler, IHttpAsyncHandler
{
    public void ProcessRequest(HttpContext context) { }

    public bool IsReusable { get { return false; } }

    private SqlConnection m_conn;
    private SqlCommand m_cmd;
    private HttpContext m_context;

    // 定义一个委托来创造异步操作返回对象
    private System.Action action;

    public IAsyncResult BeginProcessRequest(
        HttpContext context, AsyncCallback cb, object extraData)
    {

        this.m_context = context;

        if (context.Request.QueryString["xx"] != null)
        {
            this.m_conn = new SqlConnection("server=192.168.14.115;database=sms_config;uid=sa;pwd=123456;Asynchronous Processing=true");
            this.m_cmd = new SqlCommand("select 1", this.m_conn);
            try
            {
                this.m_conn.Open();
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
            }            

            IAsyncResult result = this.m_cmd.BeginExecuteNonQuery(cb, extraData);

            return result;
        }
        else
        {
            // 创建委托实例
            this.action = () => { };
            return action.BeginInvoke(cb, extraData);
        }
    }

    public void EndProcessRequest(IAsyncResult result)
    {

        this.m_context.Response.ContentType = "text/plain";

        if (this.action != null)
        {
            this.action.EndInvoke(result);

            this.m_context.Response.Write("No Data Access!");
        }
        else if (this.m_cmd != null)
        {
            this.m_cmd.EndExecuteNonQuery(result);
            this.m_conn.Dispose();

            this.m_context.Response.Write("Data Access Complete!");
        }
    }
}
